var fs = require('fs');
var path = require('path');
var readline = require('readline');
var stream = require('stream');

var main = (function () {
    var self, config;
    return {
        init: function (opts) {
            self=this;
            config=opts;
            1&&(async ()=>{
                var srcLines=await self.readline(config.src);
                var targetLines=await self.readline(config.target);
                self.compare(srcLines,targetLines);
            })();

        },
        readline:(file)=>{
            return new Promise((resolve,rejct)=>{
                var rl=readline.createInterface(fs.createReadStream(path.join(__dirname,file)),new stream());
                var lines=[];
                rl.on('line',(line)=>{
                    //console.log('line:',line);
                    line&&lines.push(line);
                });
                rl.on('close',()=>{
                    resolve(lines);
                });
            });
        },
        compare:(srcLines,targetLines)=>{
            //console.log('srcLines:',srcLines);
            //console.log('targetLines:',targetLines);
            var diff=[];
            for(let line of srcLines){
                if(!~targetLines.indexOf(line))diff.push(line);
            }
            console.log('diff:\n',diff);
            self.save(diff);
        },
        save:(diff)=>{
            fs.writeFile(path.join(__dirname,path.basename(config.src,'.txt')+'==》'+path.basename(config.target,'.txt')+'--diff.txt'),diff.join('\n\r'),(err)=>{
                if(err)throw err;
                console.log('Diff saved.');
            });
        }
    }

})();

main.init({
        src:'JS.txt',
        target:'MEAN.txt'
    }
);